#pragma once

#include <mutex>
#include <vector>
#include <memory>
#include <d3d11.h>
#include <wrl/client.h>
#include "video_renderer_interface.hpp"
#include "api/p2pms_client_interface.hpp"

namespace p2pms
{

using Microsoft::WRL::ComPtr;

class D3DVideoRenderer : public IVideoRenderer, public std::enable_shared_from_this<D3DVideoRenderer>
{
public:
	D3DVideoRenderer(const MediaInfo& media, IMainThreadExecutor* executor);
	~D3DVideoRenderer() override;

	// IVideoRenderer interface methods
	const MediaInfo& GetMediaInfo() const override { return m_media_info; }
	bool SetRenderWindow(void* window_handle) override;
	void SetVideoTrack(rtc::scoped_refptr<webrtc::VideoTrackInterface> video_track) override;
	void OnPaint() override;
	void OnWindowSizeChanged() override;
	void OnFrame(const webrtc::VideoFrame& frame) override;
	void Start() override;
	void Stop() override;

private:
	void UpdateTexture(const uint8_t* bgra_data, int width, int height);
	void Present(bool vsync);
	void HandleDeviceLost();
	void Cleanup();
	bool InitDeviceAndSwapChain();
	bool InitRenderPipeline();
	bool InitRenderTargetView();
	bool InitTexture();
	void DoRenderFrame(const uint8_t* bgra_data, int width, int height);
	void RenderFrame(const std::vector<uint8_t>& buf, int width, int height);
	void UpdateWindowSize();

private:
	// Direct3D 资源
	ComPtr<ID3D11Device> m_device;
	ComPtr<ID3D11DeviceContext> m_context;
	ComPtr<IDXGISwapChain> m_swap_chain;
	ComPtr<ID3D11RenderTargetView> m_render_target_view;
	ComPtr<ID3D11Texture2D> m_video_texture;
	ComPtr<ID3D11ShaderResourceView> m_shader_resource_view;
	ComPtr<ID3D11VertexShader> m_vertex_shader;
	ComPtr<ID3D11PixelShader> m_pixel_shader;
	ComPtr<ID3D11InputLayout> m_input_layout;
	ComPtr<ID3D11Buffer> m_vertex_buffer;
	ComPtr<ID3D11Buffer> m_index_buffer;
	ComPtr<ID3D11SamplerState> m_sampler_state;

	// 顶点缓冲区参数
	UINT m_vertex_stride = sizeof(float) * 5; // 3D 位置 + 2D 纹理坐标
	UINT m_vertex_offset = 0;

	// 渲染参数
	HWND m_hwnd = nullptr;
	int m_width = 0;
	int m_height = 0;
	int m_texture_width = 0; // 默认纹理大小
	int m_texture_height = 0;
	std::mutex m_mutex; // 保护资源访问

	std::vector<uint8_t> m_bgra_buffer;
	rtc::scoped_refptr<webrtc::VideoTrackInterface> m_video_track;
	IMainThreadExecutor* m_executor = nullptr;
	MediaInfo m_media_info;
	bool m_is_rendering = true;

	// Add to class definition in d3d_video_renderer.hpp
private:
	ComPtr<ID3D11Buffer> m_constant_buffer; // Constant buffer for scale factors
};

} // namespace p2pms